<template>
  <div id="login">
    <div class="form-wrap">
      <ul class="menu-tab">
        <li :class="{ current: current_menu === item.type }" v-for="item in tab_menu" :key="item.type"
          @click="toggleMenu(item.type)">
          {{ item.label }}
        </li>
      </ul>
      <div>
        <el-form ref="formRef" :model="form" :rules="form_rules" status-icon>
          <el-form-item prop="username">
            <label class="form-label">用户名</label>
            <el-input v-model="form.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item prop="password">
            <label class="form-label">密码</label>
            <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
          </el-form-item>
          <el-form-item v-if="current_menu === 'register'" prop="email">
            <label class="form-label">邮箱</label>
            <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          <el-form-item>
            <el-button :type="submit_button_disabled ? 'info' : 'danger'" class="el-button-block"
              :disabled="submit_button_disabled" :loading="submit_button_loading" @click="handleSubmit">
              {{ current_menu === 'login' ? '登录' : '注册' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <starry-sky :stars-count="1000" :distance="1000" />
    </div>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { validateEmail, validatePassword } from '@/utils/validate'
import useStore from '@/store'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const validate_name_rules = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    callback()
  }
}

const validate_password_rules = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!validatePassword(value)) {
    callback(new Error('请输入6-20位密码，包含数字和字母'))
  } else {
    callback()
  }
}

const validate_email_rules = (rule, value, callback) => {
  if (data.current_menu === 'login') {
    callback()
  }
  if (value === '') {
    callback(new Error('请输入邮箱'))
  } else if (!validateEmail(value)) {
    callback(new Error('邮箱格式不正确'))
  } else {
    callback()
  }
}

const data = reactive({
  tab_menu: [
    { type: 'login', label: '登录' },
    { type: 'register', label: '注册' },
  ],
  current_menu: 'login',
  form: {
    username: '',
    password: '',
    email: ''
  },
  form_rules: {
    username: [
      { required: true, validator: validate_name_rules, trigger: 'change' },
    ],
    password: [
      { required: true, validator: validate_password_rules, trigger: 'change' },
    ],
    email: [
      { required: true, validator: validate_email_rules, trigger: 'change' },
    ],
  },
  submit_button_disabled: false,
  submit_button_loading: false,
})

const formRef = ref(null)
let { tab_menu, current_menu, form, form_rules, submit_button_disabled, submit_button_loading } = toRefs(data)

const toggleMenu = (type) => {
  current_menu.value = type
  formRef.value.clearValidate()
  submit_button_disabled.value = false
}

const reset = () => {
  //重置表单
  formRef.value.resetFields()
  // 切换到登录模式
  current_menu.value = 'login'
  // 禁用登录按钮
  submit_button_disabled.value = false
  // 取消提交按钮的加载状态
  submit_button_loading.value = false
};

const register = async () => {
  const { username, password, email } = form.value

  const requestData = {
    username,
    password,
    email,
  }
  submit_button_loading.value = true
  try {
    const res = await store.app.registerAction(requestData)
    ElMessage.success(res.msg)
    // 注册成功后自动切换到登录
    reset()
    current_menu.value = 'login'
  } catch (error) {
    submit_button_loading.value = false
  }
}

const login = async () => {
  const { username, password } = form.value

  const requestData = {
    username,
    password
  }

  submit_button_loading.value = true
  try {
    const res = await store.app.loginAction(requestData)
    ElMessage.success(res.msg)
    router.push({
      name: 'Home'
    })
  } catch (error) {
    console.log('error', error);
    submit_button_loading.value = false
  }
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    console.log('valid', valid);
    if (valid) {
      current_menu.value == 'login' ? login() : register();
    }
  })
}

onBeforeUnmount(() => {
  // 清理工作
})
</script>

<style lang="scss" scoped>
#login {
  height: 100vh;
  background-color: #2d3a4b;
  position: relative;
  z-index: 1;
}

.form-wrap {
  width: 320px;
  padding-top: 100px;
  margin: auto;
}

.menu-tab {
  text-align: center;

  li {
    display: inline-block;
    padding: 10px 24px;
    margin: 0 10px;
    font-size: 18px;
    color: #999;
    cursor: pointer;
    border-bottom: 2px solid transparent;

    &.current {
      color: #fff;
      border-bottom: 2px solid #409eff;
    }
  }
}

.form-label {
  display: block;
  margin-bottom: 5px;
  color: #fff;
}

:deep(.el-input__wrapper) {
  background-color: transparent !important;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) !important;

  input {
    color: #fff;
    background-color: transparent;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5);
    }
  }
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c !important;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
}

.el-button-block {
  width: 100%;
  margin-top: 20px;
}

:deep(.el-button--info) {
  background-color: #909399;
  border-color: #909399;
  color: #fff;
}
</style>